package com.guiji.quartz.domain;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.wanghaomiao.xpath.exception.NoSuchAxisException;
import cn.wanghaomiao.xpath.exception.NoSuchFunctionException;
import cn.wanghaomiao.xpath.exception.XpathSyntaxErrorException;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.common.utils.spring.SpringUtils;
import com.guiji.quartz.formatter.DataTemplateFormatter;
import com.guiji.quartz.service.ISpiderNewsService;
import com.guiji.quartz.service.RedisService;
import com.guiji.quartz.task.DataSaveUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description: 新浪体育top20
 * @author: gaoX
 * @create: 2021-08-24 13:42
 **/
public class SinaSport20 {
	private static final Logger log = LoggerFactory.getLogger(SinaSport20.class);

	public void mainMethod() throws NoSuchFunctionException, XpathSyntaxErrorException, NoSuchAxisException {
		List<String> entry = getEntry();
		HttpResponse response = HttpRequest.get(entry.get(0))
			.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
			.header("Accept-Encoding", "gzip, deflate")
			.setConnectionTimeout(15000)
			.execute();
		String resp = response.body();
		List<String> jsUrl = getJsUrl(resp);
		getContent(jsUrl);
	}

	private static void getContent(List<String> listContent) throws NoSuchFunctionException, XpathSyntaxErrorException, NoSuchAxisException {
		for(String url:listContent){
			HttpResponse response = HttpRequest.get(url)
				.setConnectionTimeout(15000)
				.execute();
			String doc = response.body();
			JXDocument jxDocument = new JXDocument(doc);
			String title = null;
			try {
				title = (String) jxDocument.sel("//h1/text()").get(0);
			} catch (Exception e) {
				System.out.println("标题错误-------------"+url+"-------------------标题错误");
			}
			StringBuffer content = new StringBuffer();
			if(doc.contains("class=\"article\"")){
				jxDocument.sel("//div[@class='article']//p/text()").forEach(s->{
					content.append(s+"$$$");
				});
			}else if(doc.contains("class=\"datu-a\"")){
				jxDocument.sel("//div[@class='datu-a']//p/text()").forEach(s->{
					content.append(s+"$$$");
				});
			}else{
				jxDocument.sel("//div[@class='datu-a article']//p/text()").forEach(s->{
					content.append(s+"$$$");
				});
			}
			List<Object> imgs = jxDocument.sel("//div[@class='img_wrapper']//img/@src");
			List<String> newImgs = dealPic(imgs);

			Document document = Jsoup.parse(doc);
			DataTemplateFormatter dataTemplateFormatter = new DataTemplateFormatter();

			Date date = null;
			try {
				date = dataTemplateFormatter.format(document.getElementsByClass("date").toString().replaceAll("<.*?>",""));
			} catch (Exception e) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String s = sdf.format(new Date());
				date = dataTemplateFormatter.format(s+" 00:00  ");
			}

			if (content.length() > 5000 || content.toString().replaceAll("\\$|[\\s\\p{Zs}]","").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				DataSaveUtil.saveData(title, content.toString(), newImgs, url, date, "http://sports.sina.com.cn/others/", "新浪综合体育");
				log.info(Thread.currentThread().getName() + "-----------------新浪综合体育----------------");
			} catch (Exception e) {
				continue;
			}
		}
	}

	private static List<String> dealPic(List<Object> imgList){
		List<String> newImg = new ArrayList<>();
		for (Object s : imgList) {
			if (!s.toString().contains("http")) {
				String url = "https:" + s;
				try {
					String s1 = HttpUtil.get(url,15000);
					newImg.add(url);
				} catch (Exception e) {
					continue;
				}
			} else {
				try {
					String s1 = HttpUtil.get(s.toString());
					newImg.add(s.toString());
				} catch (Exception e) {
					continue;
				}
			}
		}
		return newImg;
	}

	private static List<String> getJsUrl(String content) {
		List<String> res = new ArrayList<>();//https://sports.sina.com.cn/others/pingpang/2021-09-13/doc-iktzscyx3932883.shtml
		String pattern = "https://sports.sina.com.cn/others.*?202.*?html";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(content);
		while (m.find()) {
			res.add(m.group());
		}
		return res;
	}


	public static List<String> getEntry() {
		List<String> listEntry = new ArrayList<>();
		listEntry.add("http://sports.sina.com.cn/others/");
		return listEntry;
	}
}
